<html>
<head>
    <title>Twenty Second Tutorial</title>
</head>
<body>

<p>There is one main factory class in EasierMock called <strong><a href="apidocs/org/easiermock/EasierMock.html">EasierMock</a></strong></p>


<p><strong>Note:</strong> All EasierMock classes are in the
    <strong><code>org.easiermock</code></strong> package.</p>

<h1>Overview</h1>

<p>An EasierMock is made up of a mock or stub class that you (the developer) must write and some dynamically generated code that EasierMock provides.</p>

<h2>Terminology</h2>

<p>For the purposes of this tutorial:</p>
<ul>
  <li>The developer-written class will be referred to as the "Delegate"</li>
  <li>The class being mocked will be called the "Real class"</li>
  <li>The mock object (generated by EasierMock) will be called the "Mock"</li>
</ul>

<h2>Description</h2>

<p>The role of EasierMock is to take the developer's Delegate class and provide a Mock class that provides the same interface as the Real class. There does not have to be any class-hierarchy relationship between the Delegate class and the Real class. However, it will be explained later why it usually makes sense to extend/implement the Real class with your Delegate.</p>

<p>EasierMock looks for an annotation (@Mock) to determine which methods called on the Mock object should be passed on to the Delegate. Calls to methods that are not marked with @Mock will usally throw an UnsupportedOperationException (though there is a degree of flexibility in this behaviour).</p>

<p>Imagine your Real interface looked like this:</p>

<pre>
public interface MyReal {
  public void method1();
  public void method2();
}
</pre>

<p>A basic Delegate class might look like this:</p>

<pre>
public class MyMock implements MyReal {
  @Mock
  public void method1() {
    // This is mocked - it is annotated with @Mock
  }

  public void method2() {
    // This is not mocked (there is no @Mock annotation)
    // Calls to this method will not be passed on and will result in an UnsupportedOperationException.
  }
}
</pre>

<h1>The @Mock annotation</h1>

<p>The Mock annotation can be applied to methods or classes. The purpose is to flag whether a method is a mock implementations. When applied to a class, it is treated as the equivalent of annotating all methods <em>declared directly</em> on that class with @Mock.</p>

<p>Any methods on a Real that do not have an equivalent method flagged as a Mock on the Delegate will throw UnsupportedOperationException.</p>

<h1>Should the Delegate implement the same interface/extend from the Real class?</h1>

<p>There <em>does not</em> need to be a class-hierarchy relationship between the Delegate and the Real class. EasierMock works via reflection so the only requirement is that the methods on the Delegate have the same signature as those declared on the Real class. Even though this is the case developers will often find it easier to extend or implement the Real class when writing the Delegate as this will assist when using refactoring tools to ensure that the signature of the Delegate is refactored along with the Real. Each of the options are described below.</p>

<h2>Real interfaces: Implementing the interface with a concrete delegate</h2>

<p>When the Real class is an interface and the Delegate class implements the interface with a <em>concrete</em> class there is no option for the developer but to provide empty/no-op implementations for all the methods on the interface.</p>

<p>Tools such as IntelliJ provide the ability to generate a class that throws UnsupportedOperationException, so if you are using this tool or something similar, you may find it easiest to mark the entire class with @Mock rather than only annotating the methods you have provided mock implementations for.</p>

<p>E.g.:</p>

<pre>
@Mock
public class MyDelegate implements MyReal {
  public void method1() {
    // Your mock method here
  }

  public void method2() {
    throw new UnsupportedOperationException();
  }
}
</pre>

<p>Creating the Mock looks like this:</p>

<pre>
MyReal delegate = new MyDelegate();
MyReal mockReal = EasierMock.createMock(MyReal.class, delegate);
</pre>

<h2>Real interface: Implementing the parts of the interface you want to mock, but leaving the Delegate class abstract</h2>

<p>It is also possible to leave your Delegate class as abstract. This means less code, and addresses the refactoring problem when not implementing the real interface with the Delegate. However, it does mean you need to rely on EasierMock to create the instance for you using bytecode magic.</p>

<p>E.g.:</p>

<pre>
@Mock
public abstract class MyAbstractDelegate implements MyReal {
  public void method1() {
    // Your mock method here
  }

  // All other methods left unimplmented and therefore abstract

}
</pre>

<p>Creating the Mock looks like this:</p>

<pre>
MyReal mockReal = EasierMock.createMock(MyAbstractDelegate.class);
</pre>

<p>Note: If your Delegate class has constructor that takes arguments then you can provide constructor arguments using the the overloaded versions of this method</p>

<h2>Real interface: Not implementing the interface with the Delegate class</h2>

<p>Not implementing the interface with the Delegate is potentially much less code than implementing the whole interface yourself (depending on the size of the interface being mocked). However, it suffers from the disadvantage already mentioned that refactoring could break your tests. While this should be fairly easy to spot when it happens (since your tests should break), it does mean a maintenance overhead. It is therefore recommended that you leave your Delegate abstract instead.</p>

<p>For completeness, here is the same example as above but without the inheritence:</p>

<pre>
public class MyNonImplementingDelegate {
  @Mock
  public void method1() {
    // Your mock method here
  }
}
</pre>

<h2>Real class: Extending the Real with the Delegate</h2>

<p>This case is where EasierMock really starts pulling its weight. Let's take the example of wanting to have a mock implementation of the java.io.File class. Here you can just extend and only implement the methods you intend to mock:</p>

<pre>
public class MockFile extends File {
  public MockFile() {
    super("MockFile");
  }

  @Mock
  public String getParent() {
    // Your mock method here
  }
}
</pre>

<p>All other methods receive the standard EasierMock treatment of throwing UnsupportedOperationException, which saves you from having to override them yourself to do nothing (or not override them and risk that another developer will call them incorrectly believing them to be mocked).</p>

<h2>Real class: Not extending the Real with the Delegate</h2>

<p>This option is largely the same as with interfaces. It has the same advantages and disadvantages, except that you may find cases where you <em>cannot</em> extend the Real class due to language restrictions and so you are forced to do it (e.g. if the Real class does not have a public constructor). EasierMock does not have the same restrictions as classes you write so it <em>can</em> extend from these classes (though not final classes, etc.).</p>

<h2>Real class: Extending the Real with the Delegate but leaving the Delegate abstract</h2>

<p>Why would you want to do this? Well, usually you don't need to. It only really makes sense when you want to create a Mock for an abstract class in order to test the abstract behaviour, and you don't want to create a concrete subclass just for tests.</p>

<h1>The EasierMock API</h1>

<p>Creating a Mock is a simple call to a static method.</p>

<p>With a concrete Delegate, the developer provides the Delegate and the class to be mocked.</p>

<pre>
MyDelegate delegate = new MyDelegate();
MyReal mockReal = EasierMock.createMock(MyReal.class, delegate);
</pre>


<p>With an abstract Delegate, the developer provides the Delegate class and any constructor arguments needed. EasierMock assumes there is an inheritance relationship between the Real class and the Delegate class so you do not need to provide the Real class as an argument.</p>

<pre>
MyReal mockReal = EasierMock.createMock(MyAbstractDelegate.class);
</pre>

<p>In both cases, the mockReal variable can be used in your tests in place of the Real.</p>

<h1>Other features of EasierMock</h1>

<h2>Creating concrete instances from abstract classes/interfaces</h2>

<p>EasierMock proves some method for creating a concrete instance from an abstract class. This can be used for creating basic stubs for classes without writing a new implementation for tests, and can also be useful for testing abstract classes.</p>

<p>This first form defaults some of the behaviour. The first method shown assumes your abstract class is either an interface or a class with a zero argument constructor, he second allows you to specify the constructor you want to use and provide the arguments. Calls to any abstract methods will result in an UnsupportedOperationException.</p>

<pre>
	public static <T> T createConcreteInstance(Class<T> abstractClass);
	public static <T> T createConcreteInstance(Class<T> abstractClass, Class<?>[] constructorTypes, Object[] constructorArgs) {
</pre>

<p>The second set of methods allow you to specify an InvocationHandler instance that will be called for abstract methods (rather than just defaulting the behaviour to throwing UnsupportedOperationException).</p>

<pre>
	public static <T> T createConcreteInstance(Class<T> abstractClass, InvocationHandler abstractMethodHandler) {
	public static <T> T createConcreteInstance(Class<T> abstractClass, InvocationHandler abstractMethodHandler, Class<?>[] constructorTypes, Object[] constructorArgs) {
</pre>

<h2>Call counting</h2>

<p>EasierMock provides an additional mechanism to help developers avoid writing tedious boilerplate code. Quite often you will want your delegate class to tell you whether a method has been called or how many times it was called. The other mock framework called EasyMock (that EasierMock is designed to work alongside) provides the EasyMock.expect() method to combine the method counting with test expectations. While this is very elegant, many people find it hard to use. EasierMock provides a class called CountingMethodListener which keeps a count that is incremented before a mock method is called.</p>

<p>All methods that create mocks take an optional array of MethodListeners.</p>

<pre>
CountingMethodListener methodCounter = new CountingMethodListener();
MyDelegate delegate = new MyDelegate();
MyReal mockReal = EasierMock.createMock(MyReal.class, delegate, methodCounter);
</pre>

<p>In tests, the CountingMethodListener can be queried to determine the number of calls that have been made to a method</p>

<pre>
assertEquals(5, methodCounter.getBeforeCount("methodId"));
</pre>

<p>There is one piece of the puzzle missing: Where does the string "methodId" come from? It can be specified as an optional part of the Mock annotation:</p>

<pre>
public abstract class MyDelegate implements MyReal {
  @Mock(id="methodId")
  public void method1() {
    // Your mock method here
  }
}
</pre>

<p>If you do not specify the ID with the annotation, the name of the method is used instead.</p>
<p>If a method is overloaded, or if the same ID is specified for multiple methods there is a single counter that is incremented when any of those methods are called.</p>
<p>A listener can be shared across multiple mocks.</p>
<p>Tip: The id attribute can be specified as a final static String in test code which makes it easy to maintain.</p>

<p>EasierMock doesn't provide any more than basic method invocation counting because existing frameworks like EasyMock already provide a lot of the more complex behaviour one would want beyond this. However, there is nothing to stop developers from writing more complicated implementations of MethodListener.</p>

<h2>Obtaining the Delegate from the Mock</h2>

<p>You can use the getDelegate() method on the EasierMock class to obtain the delegate for your Mock if you lose track of it, if you only want to hold references to the Mock or if the Delegate is abstract and EasierMock created it for you.</p>

<pre>
MyReal mockReal = EasierMock.createMock(MyAbstractMock.class);
...
MyAbstractMock delegate = EasierMock.getDelegate(mockReal);

</pre>

</body>
</html>